<?php
// +----------------------------------------------------------------------
// | wttai [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.wttai.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 老司机 <wutongtai@wttai.com> <http://www.wttai.com>
// +----------------------------------------------------------------------

namespace Home\Controller;
use OT\DataDictionary;

/**
 * 验证码控制器
 */
class CodeController extends HomeController {
	
	/**
	 * 获取验证码
	 */
	 public function obtain(){
	 	//$phone='18824104126';
	    $phone=I('post.phone');//手机号$rand=I('post.rand','','intval');//验证码
	 
		// var_dump(preg_match("/^1[34578]\d{9}$/", $phone));exit;
		if(!(preg_match("/^1[34578]\d{9}$/", $phone))){
			return $this->ajaxReturn(array('state'=>0,'text'=>'手机号错误'));
		}

		$code=D('Common/Code');
		//获取验证码
		$result=$code->newest($phone,1);
		
		if($result){
			$time=time();
			$time_r=$time-60;
		 	if($result['send_time'] >$time_r){
				return $this->ajaxReturn(array('state'=>0,'text'=>'一分钟不能同一个手机号不能发送二次'));
			}	 
			$codeCount=$code->code_count($phone,1,5,"1,2");
			if($codeCount>=5){
			    return $this->ajaxReturn(array('state'=>0,'text'=>'五分钟不能同一个手机号不能发送五次'));
			}
			
		}
		$codeNum=(session('codeNum')? session('codeNum'):1);

		if($codeNum<=3){
		    $codeNum+=1;
		}else{
		    return $this->ajaxReturn(array('state'=>0,'text'=>'验证码不能超过三次'));
		}
		//获取随机码
		$rand='验证码：'.code().'，全球原创设计师圆梦台！';
		
		//插入验证码记录
		$code_id=$code->code_insert($phone,1,$rand);
		if(!$code_id){
			return $this->ajaxReturn(array('state'=>0,'text'=>'验证码入库失败'));
		}
		
		
		
		//发送验证码
		$send=send($rand,$phone);
		if($send[0]==1){
			//发送成功
		    session('codeNum',$codeNum);
			$code->code_update($code_id,'2');
			return $this->ajaxReturn(array('state'=>1,'text'=>'验证码发送成功'));
		}else{
			//发送失败
			$code->code_update($code_id,'-1');
			return $this->ajaxReturn(array('state'=>0,'text'=>'验证码发送失败'));
		}
		
		
		
		//验证验证码
		$rand=$code->verification($rand,$result);
		
		if($rand[0]!=200){
			return $this->ajaxReturn(array('state'=>0,'text'=>$rand[1]));
		}
		
		return $this->ajaxReturn(array('state'=>1,'text'=>'留言成功'));
	 }
	 
}